Tengo este fragmento de código:
class MyClass { constructor(text, pattern) { this.text = text; this.pattern = pattern; } run() { return this.text.replace(/(\d)/, this.replacer) } replacer(match, timeString, offset, string) { return this.pattern; } }Es un ejemplo simplificado de mi código real.
Cuando corro:
var v = new MyClass("text 1 2", "X"); v.run();Veo el error:
TypeError no capturado: no se pueden leer las propiedades de undefined (leyendo 'patrón')
¿Cómo puede acceder a this en esta función de reemplazo?
Use Function#bind para establecer this valor, o use una función de flecha que llame a this.replacer como devolución de llamada.
class MyClass { constructor(text, pattern) { this.text = text; this.pattern = pattern; } run() { return this.text.replace(/(\d)/, this.replacer.bind(this)); // or return this.text.replace(/(\d)/, (...args) => this.replacer(...args)); } replacer(match, timeString, offset, string) { return this.pattern; } } var v = new MyClass("text 1 2", "X") console.log(v.run());